import poplib
import os
from email.parser import Parser
from email.header import decode_header
from datetime import date
from django.conf import settings

class Pop3Base:
	def __init__(self):
		self.server = settings.EMAIL_POP3_HOST
		self.port = settings.EMAIL_POP3_PORT
		self.email = settings.EMAIL_POP3_USER
		self.passwd = settings.EMAIL_POP3_PASSWORD
		self.connection = None
		self.num_of_msg = 0
		self.mails = []
		self.finded_mails = []
		self.path_to_log_file = os.path.join(os.curdir, "pop3.log")
		self.log_file = open(self.path_to_log_file, "w")
		self.log_file.write(str(date.today()) + "\n")


	def connect(self):
		server = self.server
		port = self.port
		self.connection = poplib.POP3_SSL(server, port)
		self.connection.set_debuglevel(0)
		resp = self.connection.user(self.email)
		self.log_file.write(resp + "\n")
		resp = self.connection.pass_(self.passwd)
		self.log_file.write(resp + "\n")
		resp = self.connection.getwelcome()
		self.log_file.write(resp + "\n")


	def get_nun_of_msjs(self):
		self.num_of_msg = len(self.connection.list()[1])


	def download_mails(self):
		parser = Parser()
		num = self.num_of_msg
		for msg in range(1, num +1):
			mail_download = self.connection.retr(msg)[1]	
			mail_download = '\n'.join(mail_download)
			mail = parser.parsestr(mail_download)
			self.mails.append(mail)

				
	def find_mails(self, subject_to_find):
		for mail in self.mails:
			subject = mail['Subject']
			subject = unicode(decode_header(subject)[0][0], 'latin-1')
			if subject and subject == subject_to_find:
				self.finded_mails.append(mail)

